package com.zlm.girlfriendmp.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.zlm.girlfriendmp.model.GreetingMsg;
import com.zlm.girlfriendmp.forest.RollApiClient;
import com.zlm.girlfriendmp.model.RollApiResponse;
import com.zlm.girlfriendmp.model.RollDailyWord;
import com.zlm.girlfriendmp.model.RollIpSelf;
import com.zlm.girlfriendmp.model.RollWeather;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @ClassName GreetingService
 * @Author zhuliming
 * @Date 2022/8/24 10:03
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GreetingService implements SchedulingConfigurer {

    private final WxMpService wxMpService;
    private final RollApiClient rollApiClient;
    private final GreetingMsgProperties greetingMsgProperties;

    private String[] colorArr = {"#FC667F", "#FC66E6", "#AC66FC", "#57C5F5", "#F5A857", "#F5D057", "#57CDF5"};

    /**
     * 问候类别
     */
    public enum GreetingType {
        MORNING,// 清晨问候
        COMMON; // 普通消息问候
    }

    /**
     * 配置定时任务
     *
     * @param taskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 添加清晨问候定时任务
        String morningTaskExecuteTime = greetingMsgProperties.getMorningTaskExecuteTime();
        if (StrUtil.isNotEmpty(morningTaskExecuteTime)) {
            taskRegistrar.addCronTask(() -> {
                try {
                    sendTemplateMessage(null, GreetingType.MORNING);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, morningTaskExecuteTime);
        }
        // 添加普通问候定时任务
        List<GreetingMsg> greetingMsgList = greetingMsgProperties.getCommonGreetingMsg();
        for (GreetingMsg msg : greetingMsgList) {
            String executeTime = msg.getExecuteTime();
            if (StrUtil.isNotEmpty(executeTime)) {
                taskRegistrar.addCronTask(() -> {
                    try {
                        sendTemplateMessage(msg, GreetingType.COMMON);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, executeTime);
            }
        }
    }

    /**
     * 发送模板消息
     *
     * @throws WxErrorException
     * @throws InterruptedException
     */
    public void sendTemplateMessage(GreetingMsg greetingMsg, GreetingType greetingType) throws WxErrorException, InterruptedException {
        WxMpTemplateMessage message;
        switch (greetingType) {
            case MORNING:
                message = buildMorningGreetingMessage();
                break;
            case COMMON:
                message = buildCommonGreetingMessage(greetingMsg);
                break;
            default:
                return;
        }
        // 获取关注者列表
        WxMpUserList wxMpUserList = wxMpService.getUserService().userList(null);
        // 获取关注者的openId
        List<String> openids = wxMpUserList.getOpenids();
        for (String openid : openids) {
            message.setToUser(openid);
            wxMpService.getTemplateMsgService().sendTemplateMsg(message);
        }
    }

    /**
     * 构建清晨问候消息
     *
     * @return
     * @throws InterruptedException
     */
    private WxMpTemplateMessage buildMorningGreetingMessage() throws InterruptedException {
        // 获取IP地址信息
        RollApiResponse<RollIpSelf> ipSelfRollApiResponse = rollApiClient.ipSelf();
        String city = ipSelfRollApiResponse.getData().getCity();
        Thread.sleep(1000);
        // 获取天气信息
        RollApiResponse<RollWeather> weatherRollApiResponse = rollApiClient.currentWeather(city);
        Thread.sleep(1000);
        // 获取精美句子
        RollApiResponse<List<RollDailyWord>> dailyWordRollApiResponse = rollApiClient.dailyWord(1);
        RollWeather rollWeather = weatherRollApiResponse.getData();
        // 模板数据
        List<WxMpTemplateData> templateDataList = new ArrayList<>();
        templateDataList.add(new WxMpTemplateData("date", DateUtil.formatDate(new Date()), "#FC667F"));
        templateDataList.add(new WxMpTemplateData("city", city, "#FC66E6"));
        templateDataList.add(new WxMpTemplateData("weather", rollWeather.getWeather(), "#AC66FC"));
        templateDataList.add(new WxMpTemplateData("temperature", rollWeather.getTemp(), "#57C5F5"));
        templateDataList.add(new WxMpTemplateData("love_day", computeLoveDay().toString(), "#F5A857"));
        templateDataList.add(new WxMpTemplateData("birthday1", computeBirthday(greetingMsgProperties.getTaBirthday()).toString(), "#F5D057"));
        templateDataList.add(new WxMpTemplateData("birthday2", computeBirthday(greetingMsgProperties.getMyBirthday()).toString(), "#F59957"));
        templateDataList.add(new WxMpTemplateData("note", dailyWordRollApiResponse.getData().get(0).getContent(), "#57CDF5"));
        // 构建模板消息
        return WxMpTemplateMessage
                .builder()
                .templateId(greetingMsgProperties.getTemplateId())
                .data(templateDataList)
                .build();
    }

    /**
     * 构建普通问候消息
     *
     * @param greetingMsg
     * @return
     */
    private WxMpTemplateMessage buildCommonGreetingMessage(GreetingMsg greetingMsg) {
        List<String> msgList = greetingMsg.getMsg();
        Random random = new Random();
        String msgBody = msgList.get(random.nextInt(msgList.size()));
        // 模板数据
        List<WxMpTemplateData> templateDataList = new ArrayList<>();
        templateDataList.add(new WxMpTemplateData("msg", msgBody, colorArr[random.nextInt(colorArr.length)]));
        // 构建模板消息
        return WxMpTemplateMessage
                .builder()
                .data(templateDataList)
                .templateId(greetingMsgProperties.getCommonTemplateId())
                .build();
    }

    /**
     * 计算距离生日天数
     *
     * @param day
     * @return
     */
    private Long computeBirthday(String day) {
        Date now = new Date();
        // 当前年份
        int nowYear = DateUtil.year(now);
        DateTime birthday = DateUtil.parseDate(nowYear + "-" + day);
        if (birthday.compareTo(now) < 0) {
            // 今年生日过了
            birthday = DateUtil.parseDate(++nowYear + "-" + day);
        }
        return DateUtil.between(now, birthday, DateUnit.DAY);
    }

    /**
     * 计算恋爱纪念日
     *
     * @return
     */
    private Long computeLoveDay() {
        return DateUtil.between(DateUtil.parseDate(greetingMsgProperties.getLoveDay()), new Date(), DateUnit.DAY);
    }
}
